<template>
  <div class="list-page">
    <!-- <EmergencyVerticalTabNav /> -->
    <div class="content-container">
      <div class="mb-[10px]">
        <el-card shadow="hover">
          <div style="display: flex;  align-items: center;">
            <el-radio-group v-model="queryParams.type" @change="handleTypeChange">
              <el-radio-button :label="null">全部</el-radio-button>
              <el-radio-button :label="1">现场处置</el-radio-button>
              <el-radio-button :label="2">后期处置</el-radio-button>
            </el-radio-group>
            <el-button type="primary" @click="handleAdd" style="margin-left: auto;">
               新增
            </el-button>
          </div>
        </el-card>
      </div>
      
      <!-- 列表区域 -->
      <el-card shadow="hover" class="w-full">
        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          border
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="事件描述" min-width="150" show-overflow-tooltip />
          <el-table-column prop="nodeName" label="节点名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="type" label="处置类型" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="row.type === 1 ? 'danger' : 'success'" class="status-tag">
                {{ row.type === 1 ? '现场处置' : '后期处置' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="节点状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.status === 1 ? 'warning' : 'success'" class="status-tag">
                {{ row.status === 1 ? '进行中' : '已完成' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="节点进行时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.processTime || row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="expectedHours" label="预计耗时(小时)" width="120" />
          <el-table-column prop="note" label="备注" min-width="150" show-overflow-tooltip />
          <el-table-column label="操作" width="220" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button v-if="row.status === 1" size="small" type="success" link @click="handleCompleteNode(row)">
                完成
              </el-button>
              <el-button size="small" type="danger" link @click="handleDelete(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container">
          <el-pagination
            v-if="total > 0"
            background
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 新增/编辑弹窗 -->
      <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
        append-to-body
        class="custom-dialog"
      >
        <template #header>
          <div class="dialog-header">
            <span class="dialog-title">{{ dialogTitle }}</span>
          </div>
        </template>
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="dialog-form"
        >
          <el-form-item label="关联事件" prop="eventId">
            <el-select
              v-model="form.eventId"
              placeholder="请选择关联事件"
              style="width: 100%"
              filterable
            >
              <el-option
                v-for="event in eventList"
                :key="event.id"
                :label="event.description"
                :value="event.id"
              >
                <div class="event-option">
                  <span class="event-description">{{ event.description }}</span>
                  <span class="event-time">{{ formatDateTime(event.happenTime) }}</span>
                  <el-tag size="small" :type="event.status === 1 ? 'info' : event.status === 2 ? 'warning' : 'success'">
                    {{ event.status === 1 ? '未启动' : event.status === 2 ? '进行中' : '已控制' }}
                  </el-tag>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="节点名称" prop="nodeName">
            <el-input v-model="form.nodeName" placeholder="请输入节点名称" />
          </el-form-item>
          <el-form-item label="处置类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择处置类型" style="width: 100%">
              <el-option label="现场处置" :value="1" />
              <el-option label="后期处置" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="预计耗时" prop="expectedHours">
            <el-input-number v-model="form.expectedHours" :min="0.5" :step="0.5" placeholder="请输入预计耗时(小时)" style="width: 100%" />
          </el-form-item>
          <el-form-item label="节点状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择节点状态" style="width: 100%">
              <el-option label="进行中" :value="1" />
              <el-option label="已完成" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="节点进行时间" prop="processTime">
            <el-date-picker
              v-model="form.processTime"
              type="datetime"
              placeholder="选择节点进行时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="节点类型" prop="nodeType">
            <el-select v-model="form.nodeType" placeholder="请选择节点类型" style="width: 100%">
              <el-option label="审批节点" :value="1" />
              <el-option label="处理节点" :value="2" />
              <el-option label="结束节点" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="note">
            <el-input
              type="textarea"
              v-model="form.note"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 文件预览弹窗 -->
      <el-dialog
        v-model="fileDialogVisible"
        title="相关文件"
        width="50%"
        class="file-dialog"
      >
        <div class="file-list">
          <div v-for="(file, index) in currentFiles" :key="index" class="file-item">
            <el-link :href="file" target="_blank" type="primary">
              <el-icon><Document /></el-icon>
              {{ getFileName(file) }}
            </el-link>
          </div>
        </div>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="fileDialogVisible = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { 
  getFlowList, 
  getFlowDetail, 
  addFlow, 
  updateFlow, 
  deleteFlow 
} from '@/api/bridge/command/flow';
import { getEmergencyEventById, getEmergencyEventList } from "@/api/bridge/command/event";
import dayjs from "dayjs";
import { useRouter, useRoute } from "vue-router";
import { Plus, Back, Document, Warning } from '@element-plus/icons-vue';
// import EmergencyVerticalTabNav from "@/components/EmergencyVerticalTabNav.vue";

// 路由相关
const router = useRouter();
const route = useRoute();

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const total = ref(0);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: null, // null表示全部，1表示现场处置，2表示后期处置
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = computed(() => {
  return form.value.id ? "编辑处置记录" : "新增处置记录"
});

interface FormState {
  id?: number | string;
  eventId: string;
  nodeName: string;
  type: number | null;
  expectedHours: number;
  status: number;
  processTime: string;
  nodeType: number;
  note: string;
}

// 事件列表
const eventList = ref([]);

// 获取事件列表
const getEventList = async () => {
  try {
    const res = await getEmergencyEventList({
      pageNum: 1,
      pageSize: 1000,
    });
    if (res.code === 200) {
      eventList.value = res.rows || [];
    }
  } catch (error) {
    console.error("获取事件列表失败:", error);
  }
};

const formRef = ref();
const form = ref<FormState>({
  id: undefined,
  eventId: "",
  nodeName: "",
  type: null,
  expectedHours: 1,
  status: 1,
  processTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  nodeType: 2, // 默认处理节点
  note: ""
});

// 文件预览弹窗
const fileDialogVisible = ref(false);
const currentFiles = ref([]);

// 表单校验规则
const rules = {
  eventId: [{ required: true, message: "请选择关联事件", trigger: "change" }],
  nodeName: [{ required: true, message: "请输入节点名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择处置类型", trigger: "change" }],
  expectedHours: [{ required: true, message: "请输入预计耗时", trigger: "blur" }],
  status: [{ required: true, message: "请选择节点状态", trigger: "change" }],
  processTime: [{ required: true, message: "请选择节点进行时间", trigger: "change" }],
  nodeType: [{ required: true, message: "请选择节点类型", trigger: "change" }]
};

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 获取处置阶段标签类型
const getStageTagType = (stage) => {
  const stageMap = {
    '预警': 'warning',
    '先期处置': 'info',
    '分级响应': 'primary',
    '现场处置': 'danger',
    '后期处置': 'success'
  };
  return stageMap[stage] || '';
};

// 获取文件名
const getFileName = (fileUrl) => {
  if (!fileUrl) return '';
  return fileUrl.split('/').pop() || fileUrl;
};

// 处理类型变更
const handleTypeChange = () => {
  getList();
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      type: queryParams.type
    };
    const res = await getFlowList(params);
    if (res.code === 200) {
      // 使用类型断言确保eventIds是有效的数组类型
      const eventIds = [...new Set(res.rows.map(item => item.eventId).filter(Boolean))] as (string | number)[];
      
      // 获取事件详情并添加描述
      if (eventIds.length > 0) {
        const eventDetailsPromises = eventIds.map(eventId => getEmergencyEventById(eventId));
        const eventDetailsResults = await Promise.allSettled(eventDetailsPromises);
        
        // 创建事件ID到描述的映射
        const eventDescriptionMap: Record<string, string> = {};
        eventDetailsResults.forEach((result, index) => {
          if (result.status === 'fulfilled' && result.value?.code === 200 && result.value?.data) {
            const eventId = String(eventIds[index]);
            eventDescriptionMap[eventId] = result.value.data.description;
          }
        });
        
        // 添加描述到表格数据
        tableData.value = res.rows.map(row => ({
          ...row,
          description: row.eventId ? eventDescriptionMap[String(row.eventId)] || '暂无描述' : '暂无描述'
        }));
      } else {
        tableData.value = res.rows || [];
      }
      
      total.value = res.total || 0;
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理新增
const handleAdd = async () => {
  // 获取事件列表
  await getEventList();
  
  form.value = {
    id: undefined,
    eventId: "",
    nodeName: "",
    type: queryParams.type || null,
    expectedHours: 1,
    status: 1,
    processTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    nodeType: 2,
    note: ""
  };
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row) => {
  try {
    // 获取事件列表
    await getEventList();
    
    const id = row.id || row.processFlowLogId;
    const res = await getFlowDetail(id);
    if (res.code === 200) {
      form.value = {
        ...res.data,
        processTime: res.data.processTime || res.data.createTime || dayjs().format('YYYY-MM-DD HH:mm:ss')
      };
      dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error("获取详情失败");
  }
};

// 处理完成节点
const handleCompleteNode = async (row) => {
  try {
    const id = row.id || row.processFlowLogId;
    const data = { 
      ...row, 
      status: 2, // 设置为已完成
      note: row.note || `节点"${row.nodeName}"已完成`
    };
    const res = await updateFlow(data);
    if (res.code === 200) {
      ElMessage.success('节点已完成');
      getList();
    } else {
      ElMessage.error(res.msg || '操作失败');
    }
  } catch (error) {
    console.error('完成节点失败:', error);
    ElMessage.error('操作失败');
  }
};

// 处理删除
const handleDelete = (row) => {
  const id = row.id || row.processFlowLogId;
  ElMessageBox.confirm("确认删除该处置记录吗？", "提示", {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: "warning",
  }).then(async () => {
    try {
      const res = await deleteFlow(id);
      if (res.code === 200) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error(res.msg || "删除失败");
      }
    } catch (error) {
      ElMessage.error("删除失败");
    }
  }).catch(() => {});
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = { ...form.value };
        
        if (form.value.id) {
          const res = await updateFlow(submitData);
          if (res.code === 200) {
            ElMessage.success("修改成功");
            dialogVisible.value = false;
            getList();
          } else {
            ElMessage.error(res.msg || "修改失败");
          }
        } else {
          const res = await addFlow(submitData);
          if (res.code === 200) {
            ElMessage.success("新增成功");
            dialogVisible.value = false;
            getList();
          } else {
            ElMessage.error(res.msg || "新增失败");
          }
        }
      } catch (error) {
        ElMessage.error("操作失败");
      }
    }
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getList();
};

const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getList();
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
$bg-color-page: var(--el-bg-color-page);
$bg-color-overlay: var(--el-bg-color-overlay);
$box-shadow-light: var(--el-box-shadow-light);
$box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
$border-radius: 4px;
$border-radius-dialog: 8px;
$border-color-light: var(--el-border-color-light);
$color-primary: var(--el-color-primary);
$primary-color: #409eff;
$success-color: #67c23a;
$warning-color: #e6a23c;
$danger-color: #f56c6c;
$deep-box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
$header-padding: 15px 20px;
$general-padding: 20px;
$footer-padding: 10px 20px;
$divider-color: #f0f0f0;

.list-page {
  padding: 20px;
  background: $bg-color-page;
  border-radius: $border-radius;
  box-shadow: $box-shadow-light;
  display: flex;
  gap: 20px;
}

.content-container {
  flex: 1;
  overflow: hidden;
}

.filter-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .el-radio-button {
    margin-right: 10px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 16px;
  background: $bg-color-overlay;

  :deep(th) {
    background: $bg-color-page !important;
  }
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: $bg-color-page;
  border-radius: $border-radius-dialog $border-radius-dialog 0 0;
  border-bottom: 1px solid $border-color-light;

  .dialog-title {
    font-size: 18px;
    color: #303133;
    font-weight: 600;
  }

  .action-buttons {
    display: flex;
    gap: 12px;
  }
}

.btn-group {
  .edit-btn,
  .cancel-btn,
  .save-btn {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    padding: 10px 20px;
    border-radius: 6px;
  }

  .edit-btn {
    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .cancel-btn {
    &:hover {
      background-color: #f4f4f5;
      color: #909399;
    }
  }

  .save-btn {
    padding: 10px 24px;

    &:hover {
      box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
    }
  }
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: $border-radius-dialog;
    box-shadow: $box-shadow;

    .el-dialog__body {
      padding: 24px;
      background: $bg-color-overlay;
    }

    .el-dialog__header {
      padding: 0;
      margin: 0;
    }

    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #303133;
        font-size: 24px;
        z-index: 1000;

        &:hover {
          color: $color-primary;
        }
      }
    }

    .el-dialog__footer {
      padding: 10px 20px;
      border-top: 1px solid #f0f0f0;
    }
  }
}

/* 状态标签特殊样式 */
.status-tag {
  font-weight: bold;
}

.event-option {
  display: flex;
  align-items: center;
  gap: 10px;
  
  .event-description {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .event-time {
    color: var(--el-text-color-secondary);
    font-size: 12px;
  }
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  
  .file-item {
    padding: 10px;
    border: 1px solid var(--el-border-color-light);
    border-radius: 4px;
    background-color: var(--el-bg-color);
    
    &:hover {
      background-color: var(--el-color-primary-light-9);
    }
  }
}
</style>